import React from 'react';
import { Icon } from 'antd';
import style from './index.module.less';

export default class CountTo extends React.Component<any> {
    constructor(props: any) {
        super(props);
        this.state.list = props.list;
    }

    state = {
        list: [],
        count: 0,
    };

    // 页面挂载时开启定时器
    componentDidMount = () => {
        this.contentDom = document.querySelectorAll('.textcontent');
        this.box = document.querySelector('.box');
        this.begin();
    };
    timer: any = null;
    box: any = null;
    contentDom: any = null;
    // 定时器
    begin = () => {
        this.timer = setInterval(() => {
            this.Roll();
        }, 10);
    };

    // 关闭定时器
    stop = () => {
        clearInterval(this.timer);
        this.timer = null;
    };

    // 每次向上偏移0.5px，使用state储存偏移的次数
    Roll = () => {
        this.setState({
            count: this.state.count + 0.5,
        });
        this.contentDom.forEach((item: any) => {
            item.style.transform = `translate(${-this.state.count}px, 0)`;
            const contentLeft = this.state.count;
            if (contentLeft >= item.offsetWidth) {
                this.setState({
                    count: 0,
                });
                item.style.transform = `translate(${-this.state.count}px, 0)`;
            }
        });
    };

    render() {
        return (
            <div className={`${style.box} box`} onMouseEnter={this.stop} onMouseLeave={this.begin}>
                <div className={style.icon_body}>
                    <Icon type="sound" />
                </div>
                <div className={style.content_box}>
                    <div className={`${style.content} textcontent`}>
                        {this.state.list.map((item: any, index: number) => {
                            return (
                                <span className={style.row} key={index}>
                                    {item.title}
                                </span>
                            );
                        })}
                    </div>
                    <div className={`${style.content} textcontent`}>
                        {this.state.list.map((item: any, index: number) => {
                            return (
                                <span className={style.row} key={index}>
                                    {item.title}
                                </span>
                            );
                        })}
                    </div>
                </div>
            </div>
        );
    }
}
